package com.xt.core.helper.data;

import java.lang.reflect.ParameterizedType;  
import java.lang.reflect.Type;  
   
/**
*  
*  
* @author txiao 
*/  
@SuppressWarnings("unchecked")  
public class GenericTypeUtil{  
 
    public static Class GenericTypeUtil(Class persistentClass){  
        return getSuperClassGenericType(persistentClass, 0);  
    }  
      
    /**  
     * get the class definition 
     * if nothing found, return Object 
     * 
     * @param persistentClass the class to research 
     * @param index begin from 0
     * @return  
     */  
    public static Class getSuperClassGenericType(Class persistentClass, int index){  
        boolean flag = true;  
        Type genType = persistentClass.getGenericSuperclass();  
        Type[] params = null;  
          
        if (!(genType instanceof ParameterizedType))  
            flag = false;  
        else {  
            params = ((ParameterizedType) genType).getActualTypeArguments();  
            if (index >= params.length || index < 0)  
                flag = false;  
            if (!(params[index] instanceof Class))  
                flag = false;  
        }  
        if (!flag) {  
            persistentClass = persistentClass.getSuperclass();  
            if (persistentClass == Object.class)  
                return Object.class;  
            else  
                return getSuperClassGenericType(persistentClass, index);  
        }  
          
        return (Class) params[index];  
    }  
}  
